package com.qqt.csr.route.service.strategy.cs;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.qqt.csr.common.acl.aics.AICustomerServiceClient;
import com.qqt.csr.common.acl.aics.resp.CsMemberInfoDTO;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.im.entity.Conversation;
import com.qqt.csr.im.service.AccountService;
import com.qqt.csr.im.service.RoomMemberService;
import com.qqt.csr.im.service.mongo.ConversationService;
import com.qqt.csr.route.dto.resp.RouteResultDTO;
import com.qqt.csr.route.dto.resp.SkillSetDTO;
import com.qqt.csr.route.entity.RouteBizRule;
import com.qqt.csr.route.entity.RouteTask;
import com.qqt.csr.route.enums.RouteTaskEventEnum;
import com.qqt.csr.route.service.CsReceptionLimitService;
import com.qqt.csr.route.service.CsStatusService;
import com.qqt.csr.route.service.RouteSkillSetService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客服熟客分配策略
 */
@Slf4j
@Component
public class CsLastLeastDistribution implements ICsDistribution {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ConversationService conversationService;
    @Autowired
    private RoomMemberService roomMemberService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CsStatusService csStatusService;
    @Autowired
    private AICustomerServiceClient aiCustomerServiceClient;
    @Autowired
    private CsReceptionLimitService csReceptionLimitService;
    @Autowired
    private RouteSkillSetService routeSkillSetService;

    @Override
    public void distribution(RouteTask routeTask, RouteResultDTO resultDTO) {
        if (routeTask.getRouteBizRule() == null
                || CollectionUtils.isEmpty(routeTask.getRouteBizRule().getSkillSetIdList())
                || StringUtils.isBlank(routeTask.getAccountId())) {
            return;
        }

        RouteBizRule routeBizRule = routeTask.getRouteBizRule();
        String accountId = routeTask.getAccountId();

        Date currentTime = new Date();
        Date startTime = DateUtil.offsetDay(currentTime, -routeBizRule.getAcquaintanceFirstLimit());
        Conversation lastConversation = conversationService.getLastConversationBy(accountId, DateUtil.formatDateTime(startTime), DateUtil.formatDateTime(currentTime));
        if (lastConversation == null || StringUtils.isBlank(lastConversation.getRoomId())) {
            return;
        }

        JSONObject conversationExt = JsonUtil.toObject(lastConversation.getExt(), JSONObject.class);
        if (conversationExt == null) {
            return;
        }
        String tenantId = conversationExt.getString("tenantId");
        Long skillSetId = conversationExt.getLong("skillSetId");
        Long csId = conversationExt.getLong("csId");
        List<Long> readyNormalCsIdList = csStatusService.getReadyNormalCsIdList(skillSetId);
        if (!readyNormalCsIdList.contains(csId)) {
            return;
        }
        List<CsMemberInfoDTO> csMemberInfoDtoList = aiCustomerServiceClient.getNormalListBy(Lists.newArrayList(csId))
                .stream()
                .peek(m -> m.setReceptionLimit(m.getReceptionLimit() == null ? 0 : m.getReceptionLimit()))
                .filter(m -> m.getReceptionLimit() > 0)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(csMemberInfoDtoList)) {
            return;
        }

        CsMemberInfoDTO csMemberInfoDTO = csMemberInfoDtoList.get(0);
        List<SkillSetDTO> skillSetDTOList = routeSkillSetService.getSkillSetDTOList(tenantId, Lists.newArrayList(skillSetId));
        if (CollectionUtils.isNotEmpty(skillSetDTOList)
                && csReceptionLimitService.allocate(csMemberInfoDTO, 1)) {
            // 分配成功
            resultDTO.setCsInfo(csMemberInfoDTO);
            resultDTO.setSkillSetDTO(skillSetDTOList.get(0));
            routeTask.setCsId(csMemberInfoDTO.getUserId());
            routeTask.bindSkillSet(skillSetDTOList.get(0));
            routeTask.addEvent(RouteTaskEventEnum.DIRECTLY_SEAT);
        }
    }

}
